<?php


namespace App\Services;


use App\Enums\HttpCode;
use Gregwar\Captcha\CaptchaBuilder;

class VerifyService
{
    /**
     * 生成验证码
     * @param int $length
     * @param string $charset
     * @return string
     */
    public static function generateVerifyCode($length = 5, $charset = 'abcdefghjkmnpqrstuvwxyz23456789')
    {
        $phrase = '';
        $chars = str_split($charset);
        for ($i = 0; $i < $length; $i++) {
            $phrase .= $chars[array_rand($chars)];
        }
        return $phrase;
    }

    /**
     * 检验图形码
     *
     * @param $verifyGuid
     * @param $code
     * @param string $sessionKey
     * @return bool
     */
    public static function checkImgVerify($verifyGuid, $code, $sessionKey = 'verifyGuid')
    {
        abort_if(empty($verifyGuid), 'verify_code', '校验码错误');
        $codeCheck = \Session::get($sessionKey . '.img.verify.code', null);
        abort_if(md5($verifyGuid . strtolower($code)) !== $codeCheck, HttpCode::SERVER_ERROR, '验证码错误');
        return true;
    }

    /**
     * 生成图形验证码
     *
     * @param $sessionKey
     * @param $verifyGuid
     * @return string
     */
    public static function getImgVerifyBase64($verifyGuid, $sessionKey = 'verifyGuid')
    {
        $verifyCode = self::generateVerifyCode(4);
        $builder = new CaptchaBuilder($verifyCode);
        $builder->setBackgroundColor(245, 247, 250);
        //可以设置图片宽高及字体
        $builder->build($width = 108, $height = 40, $font = null);
        \Session::put($sessionKey . '.img.verify.code', md5($verifyGuid . strtolower($builder->getPhrase())));
        return $builder->inline();
    }
}
